<!-- HTML header for doxygen 1.8.6-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=9">
<meta name="generator" content="Doxygen 1.8.13">
<title>OpenCV：矩阵的掩码操作</title>
<link href="../../opencv.ico" rel="shortcut icon" type="image/x-icon">
<link href="../../tabs.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<script type="text/javascript" src="../../tutorial-utils.js"></script>
<link href="../../search/search.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="../../search/searchdata.js"></script>
<script type="text/javascript" src="../../search/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"],
    jax: ["input/TeX","output/HTML-CSS"],
});
//<![CDATA[
MathJax.Hub.Config(
{
  TeX: {
      Macros: {
          matTT: [ "\\[ \\left|\\begin{array}{ccc} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{array}\\right| \\]", 9],
          fork: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ \\end{array} \\right.", 4],
          forkthree: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ \\end{array} \\right.", 6],
          forkfour: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ #7 & \\mbox{#8}\\\\ \\end{array} \\right.", 8],
          vecthree: ["\\begin{bmatrix} #1\\\\ #2\\\\ #3 \\end{bmatrix}", 3],
          vecthreethree: ["\\begin{bmatrix} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{bmatrix}", 9],
          cameramatrix: ["#1 = \\begin{bmatrix} f_x & 0 & c_x\\\\ 0 & f_y & c_y\\\\ 0 & 0 & 1 \\end{bmatrix}", 1],
          distcoeffs: ["(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \\tau_x, \\tau_y]]]]) \\text{ of 4, 5, 8, 12 or 14 elements}"],
          distcoeffsfisheye: ["(k_1, k_2, k_3, k_4)"],
          hdotsfor: ["\\dots", 1],
          mathbbm: ["\\mathbb{#1}", 1],
          bordermatrix: ["\\matrix{#1}", 1]
      }
  }
}
);
//]]>
</script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js"></script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css">
<link href="../../stylesheet.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<!--#include virtual="/google-search.html"-->
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="../../opencv-logo-small.png"></td>
  <td style="padding-left: 0.5em;">
   <div id="projectname">OpenCV
   &#160;<span id="projectnumber">4.5.2</span>
   </div>
   <div id="projectbrief">Open Source Computer Vision</div>
  </td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "../../search",false,'Search');
</script>
<script type="text/javascript" src="../../menudata.js"></script>
<script type="text/javascript" src="../../menu.js"></script>
<script type="text/javascript">
$(function() {
  initMenu('../../',true,false,'search.php','Search');
  $(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div id="nav-path" class="navpath">
  <ul>
<li class="navelem"><a class="el" href="../../d9/df8/tutorial_root.html">OpenCV Tutorials</a></li><li class="navelem"><a class="el" href="../../de/d7a/tutorial_table_of_content_core.html">The Core Functionality (core module)</a></li>  </ul>
</div>
</div><!-- top -->
<div class="header">
  <div class="headertitle">
<div class="title">Mask operations on matrices(矩阵的掩码运算)</div>  </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p><b>上一个教程：</b> <a class="el" href="../../db/da5/tutorial_how_to_scan_images.html">How to scan images, lookup tables and time measurement with OpenCV</a></p>
<p><b>下一个教程：</b> <a class="el" href="../../d5/d98/tutorial_mat_operations.html">Operations with images</a></p>
<table class="doxtable">
<tr>
<th align="right"></th><th align="left"></th></tr>
<tr>
<td align="right">原作者</td><td align="left">Bernát Gábor</td></tr>
<tr>
<td align="right">兼容性</td><td align="left">OpenCV &gt;= 3.0</td></tr>
</table>
<p>矩阵上的掩码操作非常简单。其思想是我们根据掩模矩阵（也称为内核）重新计算图像中每个像素的值。此遮罩包含的值将调整相邻像素（和当前像素）对新像素值的影响程度。从数学的观点来看，我们用指定的值作加权平均。</p>
<h2>我们的测试用例</h2>
<p>让我们考虑一下图像对比度增强方法的问题。基本上，我们要对图像的每个像素应用以下公式：</p>
<p class="formulaDsp">\[I(i,j) = 5*I(i,j) - [ I(i-1,j) + I(i+1,j) + I(i,j-1) + I(i,j+1)]\]</p>
 <p class="formulaDsp">\[\iff I(i,j)*M, \text{where } M = \bordermatrix{ _i\backslash ^j &amp; -1 &amp; 0 &amp; +1 \cr -1 &amp; 0 &amp; -1 &amp; 0 \cr 0 &amp; -1 &amp; 5 &amp; -1 \cr +1 &amp; 0 &amp; -1 &amp; 0 \cr }\]</p>
<p>第一种表示法是使用公式，而第二种表示法是使用掩码的第一种表示法的压缩版本。使用遮罩的方法是将遮罩矩阵的中心（大写时用零索引表示）放在要计算的像素上，然后将像素值乘以重叠的矩阵值求和。这是同样的事情，但是在大矩阵的情况下，后一种表示法更容易查看。</p>
<h2>代码</h2>
 <div class="newInnerHTML" title="cpp" style="display: none;">C++</div><div class="toggleable_div label_cpp" style="display: none;"><p>您可以从下载此源代码<a href="https://raw.githubusercontent.com/opencv/opencv/master/samples/cpp/tutorial_code/core/mat_mask_operations/mat_mask_operations.cpp">在这里</a>或者查看OpenCV源代码库示例目录<code>samples/cpp/tutorial_code/core/mat_mask_operations/mat_mask_operations.cpp</code>.</p><div class="fragment"><div class="line"><span class="preprocessor">#include &lt;<a class="code" href="../../d6/d87/imgcodecs_8hpp.html">opencv2/imgcodecs.hpp</a>&gt;</span></div><div class="line"><span class="preprocessor">#include &lt;<a class="code" href="../../d4/dd5/highgui_8hpp.html">opencv2/highgui.hpp</a>&gt;</span></div><div class="line"><span class="preprocessor">#include &lt;<a class="code" href="../../d1/d4f/imgproc_2include_2opencv2_2imgproc_8hpp.html">opencv2/imgproc.hpp</a>&gt;</span></div><div class="line"><span class="preprocessor">#include &lt;iostream&gt;</span></div><div class="line"></div><div class="line"><span class="keyword">using namespace </span><a class="code" href="../../d8/dcc/namespacestd.html">std</a>;</div><div class="line"><span class="keyword">using namespace </span><a class="code" href="../../d2/d75/namespacecv.html">cv</a>;</div><div class="line"></div><div class="line"><span class="keyword">static</span> <span class="keywordtype">void</span> help(<span class="keywordtype">char</span>* progName)</div><div class="line">{</div><div class="line">    cout &lt;&lt; endl</div><div class="line">        &lt;&lt;  <span class="stringliteral">&quot;This program shows how to filter images with mask: the write it yourself and the&quot;</span></div><div class="line">        &lt;&lt; <span class="stringliteral">&quot;filter2d way. &quot;</span> &lt;&lt; endl</div><div class="line">        &lt;&lt;  <span class="stringliteral">&quot;Usage:&quot;</span>                                                                        &lt;&lt; endl</div><div class="line">        &lt;&lt; progName &lt;&lt; <span class="stringliteral">&quot; [image_path -- default lena.jpg] [G -- grayscale] &quot;</span>        &lt;&lt; endl &lt;&lt; endl;</div><div class="line">}</div><div class="line"></div><div class="line"></div><div class="line"><span class="keywordtype">void</span> Sharpen(<span class="keyword">const</span> <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a>&amp; myImage,<a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a>&amp; Result);</div><div class="line"></div><div class="line"><span class="keywordtype">int</span> main( <span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>* argv[])</div><div class="line">{</div><div class="line">    help(argv[0]);</div><div class="line">    <span class="keyword">const</span> <span class="keywordtype">char</span>* filename = argc &gt;=2 ? argv[1] : <span class="stringliteral">&quot;lena.jpg&quot;</span>;</div><div class="line"></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> src, dst0, dst1;</div><div class="line"></div><div class="line">    <span class="keywordflow">if</span> (argc &gt;= 3 &amp;&amp; !strcmp(<span class="stringliteral">&quot;G&quot;</span>, argv[2]))</div><div class="line">        src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">imread</a>( <a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">samples::findFile</a>( filename ), <a class="code" href="../../d8/d6a/group__imgcodecs__flags.html#gga61d9b0126a3e57d9277ac48327799c80ae29981cfc153d3b0cef5c0daeedd2125">IMREAD_GRAYSCALE</a>);</div><div class="line">    <span class="keywordflow">else</span></div><div class="line">        src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">imread</a>( <a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">samples::findFile</a>( filename ), <a class="code" href="../../d8/d6a/group__imgcodecs__flags.html#gga61d9b0126a3e57d9277ac48327799c80af660544735200cbe942eea09232eb822">IMREAD_COLOR</a>);</div><div class="line"></div><div class="line">    <span class="keywordflow">if</span> (src.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#abbec3525a852e77998aba034813fded4">empty</a>())</div><div class="line">    {</div><div class="line">        cerr &lt;&lt; <span class="stringliteral">&quot;Can&#39;t open image [&quot;</span>  &lt;&lt; filename &lt;&lt; <span class="stringliteral">&quot;]&quot;</span> &lt;&lt; endl;</div><div class="line">        <span class="keywordflow">return</span> EXIT_FAILURE;</div><div class="line">    }</div><div class="line"></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5afdf8410934fd099df85c75b2e0888b">namedWindow</a>(<span class="stringliteral">&quot;Input&quot;</span>, <a class="code" href="../../d0/d90/group__highgui__window__flags.html#ggabf7d2c5625bc59ac130287f925557ac3acf621ace7a54954cbac01df27e47228f">WINDOW_AUTOSIZE</a>);</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5afdf8410934fd099df85c75b2e0888b">namedWindow</a>(<span class="stringliteral">&quot;Output&quot;</span>, <a class="code" href="../../d0/d90/group__highgui__window__flags.html#ggabf7d2c5625bc59ac130287f925557ac3acf621ace7a54954cbac01df27e47228f">WINDOW_AUTOSIZE</a>);</div><div class="line"></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( <span class="stringliteral">&quot;Input&quot;</span>, src );</div><div class="line">    <span class="keywordtype">double</span> t = (double)<a class="code" href="../../db/de0/group__core__utils.html#gae73f58000611a1af25dd36d496bf4487">getTickCount</a>();</div><div class="line"></div><div class="line">    Sharpen( src, dst0 );</div><div class="line"></div><div class="line">    t = ((double)<a class="code" href="../../db/de0/group__core__utils.html#gae73f58000611a1af25dd36d496bf4487">getTickCount</a>() - t)/<a class="code" href="../../db/de0/group__core__utils.html#ga705441a9ef01f47acdc55d87fbe5090c">getTickFrequency</a>();</div><div class="line">    cout &lt;&lt; <span class="stringliteral">&quot;Hand written function time passed in seconds: &quot;</span> &lt;&lt; t &lt;&lt; endl;</div><div class="line"></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( <span class="stringliteral">&quot;Output&quot;</span>, dst0 );</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">waitKey</a>();</div><div class="line"></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> kernel = (<a class="code" href="../../df/dfc/classcv_1_1Mat__.html">Mat_&lt;char&gt;</a>(3,3) &lt;&lt;  0, -1,  0,</div><div class="line">                                   -1,  5, -1,</div><div class="line">                                    0, -1,  0);</div><div class="line"></div><div class="line">    t = (double)<a class="code" href="../../db/de0/group__core__utils.html#gae73f58000611a1af25dd36d496bf4487">getTickCount</a>();</div><div class="line"></div><div class="line">    <a class="code" href="../../d5/df1/group__imgproc__hal__functions.html#ga42c2468ab3a1238fbf48458c57169081">filter2D</a>( src, dst1, src.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a8da9f853b6f3a29d738572fd1ffc44c0">depth</a>(), kernel );</div><div class="line">    t = ((double)<a class="code" href="../../db/de0/group__core__utils.html#gae73f58000611a1af25dd36d496bf4487">getTickCount</a>() - t)/<a class="code" href="../../db/de0/group__core__utils.html#ga705441a9ef01f47acdc55d87fbe5090c">getTickFrequency</a>();</div><div class="line">    cout &lt;&lt; <span class="stringliteral">&quot;Built-in filter2D time passed in seconds:     &quot;</span> &lt;&lt; t &lt;&lt; endl;</div><div class="line"></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( <span class="stringliteral">&quot;Output&quot;</span>, dst1 );</div><div class="line"></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">waitKey</a>();</div><div class="line">    <span class="keywordflow">return</span> EXIT_SUCCESS;</div><div class="line">}</div><div class="line"><span class="keywordtype">void</span> Sharpen(<span class="keyword">const</span> <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a>&amp; myImage,<a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a>&amp; Result)</div><div class="line">{</div><div class="line">    <a class="code" href="../../db/de0/group__core__utils.html#gaf62bcd90f70e275191ab95136d85906b">CV_Assert</a>(myImage.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a8da9f853b6f3a29d738572fd1ffc44c0">depth</a>() == <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga32b18d904ee2b1731a9416a8eef67d06">CV_8U</a>);  <span class="comment">// accept only uchar images</span></div><div class="line"><span class="comment"></span></div><div class="line">    <span class="keyword">const</span> <span class="keywordtype">int</span> nChannels = myImage.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#aa11336b9ac538e0475d840657ce164be">channels</a>();</div><div class="line">    Result.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a55ced2c8d844d683ea9a725c60037ad0">create</a>(myImage.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a146f8e8dda07d1365a575ab83d9828d1">size</a>(),myImage.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#af2d2652e552d7de635988f18a84b53e5">type</a>());</div><div class="line"></div><div class="line">    <span class="keywordflow">for</span>(<span class="keywordtype">int</span> j = 1 ; j &lt; myImage.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#abed816466c45234254d25bc59c31245e">rows</a>-1; ++j)</div><div class="line">    {</div><div class="line">        <span class="keyword">const</span> <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>* previous = myImage.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a13acd320291229615ef15f96ff1ff738">ptr</a>&lt;<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>&gt;(j - 1);</div><div class="line">        <span class="keyword">const</span> <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>* current  = myImage.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a13acd320291229615ef15f96ff1ff738">ptr</a>&lt;<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>&gt;(j    );</div><div class="line">        <span class="keyword">const</span> <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>* next     = myImage.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a13acd320291229615ef15f96ff1ff738">ptr</a>&lt;<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>&gt;(j + 1);</div><div class="line"></div><div class="line">        <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>* output = Result.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a13acd320291229615ef15f96ff1ff738">ptr</a>&lt;<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>&gt;(j);</div><div class="line"></div><div class="line">        <span class="keywordflow">for</span>(<span class="keywordtype">int</span> i= nChannels;i &lt; nChannels*(myImage.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#aa3e5a47585c9ef6a0842556739155e3e">cols</a>-1); ++i)</div><div class="line">        {</div><div class="line">            *output++ = <a class="code" href="../../db/de0/group__core__utils.html#gab93126370b85fda2c8bfaf8c811faeaf">saturate_cast</a>&lt;<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>&gt;(5*current[i]</div><div class="line">                         -current[i-nChannels] - current[i+nChannels] - previous[i] - next[i]);</div><div class="line">        }</div><div class="line">    }</div><div class="line"></div><div class="line">    Result.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a4b22e1c23af7a7f2eef8fa478cfa7434">row</a>(0).<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a0440e2a164c0b0d8462fb1e487be9876">setTo</a>(<a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">    Result.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a4b22e1c23af7a7f2eef8fa478cfa7434">row</a>(Result.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#abed816466c45234254d25bc59c31245e">rows</a>-1).<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a0440e2a164c0b0d8462fb1e487be9876">setTo</a>(<a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">    Result.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a23df02a07ffbfa4aa59c19bc003919fe">col</a>(0).<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a0440e2a164c0b0d8462fb1e487be9876">setTo</a>(<a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">    Result.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a23df02a07ffbfa4aa59c19bc003919fe">col</a>(Result.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#aa3e5a47585c9ef6a0842556739155e3e">cols</a>-1).<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a0440e2a164c0b0d8462fb1e487be9876">setTo</a>(<a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">}</div></div><!-- fragment -->  </div>  <div class="newInnerHTML" title="java" style="display: none;">Java</div><div class="toggleable_div label_java" style="display: none;"><p>您可以从下载此源代码<a href="https://raw.githubusercontent.com/opencv/opencv/master/samples/java/tutorial_code/core/mat_mask_operations/MatMaskOperations.java">在这里</a>或者查看OpenCV源代码库示例目录<code>samples/java/tutorial_code/core/mat_mask_operations/MatMaskOperations.java</code>.</p><div class="fragment"><div class="line"><span class="keyword">import</span> org.opencv.core.Core;</div><div class="line"><span class="keyword">import</span> org.opencv.core.CvType;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Mat;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Scalar;</div><div class="line"><span class="keyword">import</span> org.opencv.highgui.HighGui;</div><div class="line"><span class="keyword">import</span> org.opencv.imgcodecs.Imgcodecs;</div><div class="line"><span class="keyword">import</span> org.opencv.imgproc.Imgproc;</div><div class="line"></div><div class="line"><span class="keyword">class </span>MatMaskOperationsRun {</div><div class="line"></div><div class="line">    <span class="keyword">public</span> <span class="keywordtype">void</span> run(<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>[] args) {</div><div class="line"></div><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> filename = <span class="stringliteral">&quot;../data/lena.jpg&quot;</span>;</div><div class="line"></div><div class="line">        <span class="keywordtype">int</span> img_codec = Imgcodecs.IMREAD_COLOR;</div><div class="line">        <span class="keywordflow">if</span> (args.length != 0) {</div><div class="line">            filename = args[0];</div><div class="line">            <span class="keywordflow">if</span> (args.length &gt;= 2 &amp;&amp; args[1].equals(<span class="stringliteral">&quot;G&quot;</span>))</div><div class="line">                img_codec = Imgcodecs.IMREAD_GRAYSCALE;</div><div class="line">        }</div><div class="line"></div><div class="line">        Mat src = Imgcodecs.imread(filename, img_codec);</div><div class="line"></div><div class="line">        <span class="keywordflow">if</span> (src.empty()) {</div><div class="line">            System.out.println(<span class="stringliteral">&quot;Can&#39;t open image [&quot;</span> + filename + <span class="stringliteral">&quot;]&quot;</span>);</div><div class="line">            System.out.println(<span class="stringliteral">&quot;Program Arguments: [image_path -- default ../data/lena.jpg] [G -- grayscale]&quot;</span>);</div><div class="line">            System.exit(-1);</div><div class="line">        }</div><div class="line"></div><div class="line">        HighGui.namedWindow(<span class="stringliteral">&quot;Input&quot;</span>, HighGui.WINDOW_AUTOSIZE);</div><div class="line">        HighGui.namedWindow(<span class="stringliteral">&quot;Output&quot;</span>, HighGui.WINDOW_AUTOSIZE);</div><div class="line"></div><div class="line">        HighGui.imshow( <span class="stringliteral">&quot;Input&quot;</span>, src );</div><div class="line">        <span class="keywordtype">double</span> t = System.currentTimeMillis();</div><div class="line"></div><div class="line">        Mat dst0 = sharpen(src, <span class="keyword">new</span> Mat());</div><div class="line"></div><div class="line">        t = ((double) System.currentTimeMillis() - t) / 1000;</div><div class="line">        System.out.println(<span class="stringliteral">&quot;Hand written function time passed in seconds: &quot;</span> + t);</div><div class="line"></div><div class="line">        HighGui.imshow( <span class="stringliteral">&quot;Output&quot;</span>, dst0 );</div><div class="line">        HighGui.moveWindow(<span class="stringliteral">&quot;Output&quot;</span>, 400, 400);</div><div class="line">        HighGui.waitKey();</div><div class="line"></div><div class="line">        Mat kern = <span class="keyword">new</span> Mat(3, 3, CvType.CV_8S);</div><div class="line">        <span class="keywordtype">int</span> row = 0, col = 0;</div><div class="line">        kern.put(row, col, 0, -1, 0, -1, 5, -1, 0, -1, 0);</div><div class="line"></div><div class="line">        t = System.currentTimeMillis();</div><div class="line"></div><div class="line">        Mat dst1 = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.filter2D(src, dst1, src.depth(), kern);</div><div class="line">        t = ((double) System.currentTimeMillis() - t) / 1000;</div><div class="line">        System.out.println(<span class="stringliteral">&quot;Built-in filter2D time passed in seconds:     &quot;</span> + t);</div><div class="line"></div><div class="line">        HighGui.imshow( <span class="stringliteral">&quot;Output&quot;</span>, dst1 );</div><div class="line"></div><div class="line">        HighGui.waitKey();</div><div class="line">        System.exit(0);</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keywordtype">double</span> <a class="code" href="../../d6/d7d/namespacecv_1_1gapi_1_1own.html#a731d72310c89b732dcba8248d7b600b1">saturate</a>(<span class="keywordtype">double</span> x) {</div><div class="line">        <span class="keywordflow">return</span> x &gt; 255.0 ? 255.0 : (x &lt; 0.0 ? 0.0 : x);</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="keyword">public</span> Mat sharpen(Mat myImage, Mat Result) {</div><div class="line">        myImage.convertTo(myImage, CvType.CV_8U);</div><div class="line"></div><div class="line">        <span class="keywordtype">int</span> nChannels = myImage.channels();</div><div class="line">        Result.create(myImage.size(), myImage.type());</div><div class="line"></div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> j = 1; j &lt; myImage.rows() - 1; ++j) {</div><div class="line">            <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 1; i &lt; myImage.cols() - 1; ++i) {</div><div class="line">                <span class="keywordtype">double</span> <a class="code" href="../../d2/de8/group__core__array.html#ga716e10a2dd9e228e4d3c95818f106722">sum</a>[] = <span class="keyword">new</span> <span class="keywordtype">double</span>[nChannels];</div><div class="line"></div><div class="line">                <span class="keywordflow">for</span> (<span class="keywordtype">int</span> k = 0; k &lt; nChannels; ++k) {</div><div class="line"></div><div class="line">                    <span class="keywordtype">double</span> top = -myImage.get(j - 1, i)[k];</div><div class="line">                    <span class="keywordtype">double</span> bottom = -myImage.get(j + 1, i)[k];</div><div class="line">                    <span class="keywordtype">double</span> center = (5 * myImage.get(j, i)[k]);</div><div class="line">                    <span class="keywordtype">double</span> left = -myImage.get(j, i - 1)[k];</div><div class="line">                    <span class="keywordtype">double</span> right = -myImage.get(j, i + 1)[k];</div><div class="line"></div><div class="line">                    sum[k] = <a class="code" href="../../d6/d7d/namespacecv_1_1gapi_1_1own.html#a731d72310c89b732dcba8248d7b600b1">saturate</a>(top + bottom + center + left + right);</div><div class="line">                }</div><div class="line"></div><div class="line">                Result.put(j, i, sum);</div><div class="line">            }</div><div class="line">        }</div><div class="line"></div><div class="line">        Result.row(0).setTo(<span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">        Result.row(Result.rows() - 1).setTo(<span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">        Result.col(0).setTo(<span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">        Result.col(Result.cols() - 1).setTo(<span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line"></div><div class="line">        <span class="keywordflow">return</span> Result;</div><div class="line">    }</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="keyword">class </span>MatMaskOperations {</div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keywordtype">void</span> main(<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>[] args) {</div><div class="line">        <span class="comment">// Load the native library.</span></div><div class="line">        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);</div><div class="line">        <span class="keyword">new</span> MatMaskOperationsRun().run(args);</div><div class="line">    }</div><div class="line">}</div></div><!-- fragment -->  </div>  <div class="newInnerHTML" title="python" style="display: none;">Python</div><div class="toggleable_div label_python" style="display: none;"><p>您可以从下载此源代码<a href="https://raw.githubusercontent.com/opencv/opencv/master/samples/python/tutorial_code/core/mat_mask_operations/mat_mask_operations.py">在这里</a>或者查看OpenCV源代码库示例目录<code>samples/python/tutorial_code/core/mat_mask_operations/mat_mask_operations.py</code>.</p><div class="fragment"><div class="line"><span class="keyword">from</span> __future__ <span class="keyword">import</span> print_function</div><div class="line"><span class="keyword">import</span> sys</div><div class="line"><span class="keyword">import</span> time</div><div class="line"></div><div class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</div><div class="line"><span class="keyword">import</span> cv2 <span class="keyword">as</span> cv</div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">def </span>is_grayscale(my_image):</div><div class="line">    <span class="keywordflow">return</span> len(my_image.shape) &lt; 3</div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">def </span>saturated(sum_value):</div><div class="line">    <span class="keywordflow">if</span> sum_value &gt; 255:</div><div class="line">        sum_value = 255</div><div class="line">    <span class="keywordflow">if</span> sum_value &lt; 0:</div><div class="line">        sum_value = 0</div><div class="line"></div><div class="line">    <span class="keywordflow">return</span> sum_value</div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">def </span>sharpen(my_image):</div><div class="line">    <span class="keywordflow">if</span> is_grayscale(my_image):</div><div class="line">        height, width = my_image.shape</div><div class="line">    <span class="keywordflow">else</span>:</div><div class="line">        my_image = <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cv.cvtColor</a>(my_image, cv.CV_8U)</div><div class="line">        height, width, n_channels = my_image.shape</div><div class="line"></div><div class="line">    result = np.zeros(my_image.shape, my_image.dtype)</div><div class="line">    </div><div class="line">    <span class="keywordflow">for</span> j <span class="keywordflow">in</span> range(1, height - 1):</div><div class="line">        <span class="keywordflow">for</span> i <span class="keywordflow">in</span> range(1, width - 1):</div><div class="line">            <span class="keywordflow">if</span> is_grayscale(my_image):</div><div class="line">                sum_value = 5 * my_image[j, i] - my_image[j + 1, i] - my_image[j - 1, i] \</div><div class="line">                            - my_image[j, i + 1] - my_image[j, i - 1]</div><div class="line">                result[j, i] = saturated(sum_value)</div><div class="line">            <span class="keywordflow">else</span>:</div><div class="line">                <span class="keywordflow">for</span> k <span class="keywordflow">in</span> range(0, n_channels):</div><div class="line">                    sum_value = 5 * my_image[j, i, k] - my_image[j + 1, i, k]  \</div><div class="line">                                - my_image[j - 1, i, k] - my_image[j, i + 1, k]\</div><div class="line">                                - my_image[j, i - 1, k]</div><div class="line">                    result[j, i, k] = saturated(sum_value)</div><div class="line">    </div><div class="line">    <span class="keywordflow">return</span> result</div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">def </span>main(argv):</div><div class="line">    filename = <span class="stringliteral">&#39;lena.jpg&#39;</span></div><div class="line"></div><div class="line">    img_codec = cv.IMREAD_COLOR</div><div class="line">    <span class="keywordflow">if</span> argv:</div><div class="line">        filename = sys.argv[1]</div><div class="line">        <span class="keywordflow">if</span> len(argv) &gt;= 2 <span class="keywordflow">and</span> sys.argv[2] == <span class="stringliteral">&quot;G&quot;</span>:</div><div class="line">            img_codec = cv.IMREAD_GRAYSCALE</div><div class="line"></div><div class="line">    src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">cv.imread</a>(<a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">cv.samples.findFile</a>(filename), img_codec)</div><div class="line"></div><div class="line">    <span class="keywordflow">if</span> src <span class="keywordflow">is</span> <span class="keywordtype">None</span>:</div><div class="line">        <a class="code" href="../../df/d57/namespacecv_1_1dnn.html#a701210a0203f2786cbfd04b2bd56da47">print</a>(<span class="stringliteral">&quot;Can&#39;t open image [&quot;</span> + filename + <span class="stringliteral">&quot;]&quot;</span>)</div><div class="line">        <a class="code" href="../../df/d57/namespacecv_1_1dnn.html#a701210a0203f2786cbfd04b2bd56da47">print</a>(<span class="stringliteral">&quot;Usage:&quot;</span>)</div><div class="line">        <a class="code" href="../../df/d57/namespacecv_1_1dnn.html#a701210a0203f2786cbfd04b2bd56da47">print</a>(<span class="stringliteral">&quot;mat_mask_operations.py [image_path -- default lena.jpg] [G -- grayscale]&quot;</span>)</div><div class="line">        <span class="keywordflow">return</span> -1</div><div class="line"></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5afdf8410934fd099df85c75b2e0888b">cv.namedWindow</a>(<span class="stringliteral">&quot;Input&quot;</span>, cv.WINDOW_AUTOSIZE)</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5afdf8410934fd099df85c75b2e0888b">cv.namedWindow</a>(<span class="stringliteral">&quot;Output&quot;</span>, cv.WINDOW_AUTOSIZE)</div><div class="line"></div><div class="line">    <a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&quot;Input&quot;</span>, src)</div><div class="line">    t = round(time.time())</div><div class="line"></div><div class="line">    dst0 = sharpen(src)</div><div class="line"></div><div class="line">    t = (time.time() - t)</div><div class="line">    <a class="code" href="../../df/d57/namespacecv_1_1dnn.html#a701210a0203f2786cbfd04b2bd56da47">print</a>(<span class="stringliteral">&quot;Hand written function time passed in seconds: %s&quot;</span> % t)</div><div class="line"></div><div class="line">    <a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&quot;Output&quot;</span>, dst0)</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">cv.waitKey</a>()</div><div class="line"></div><div class="line">    t = time.time()</div><div class="line">    </div><div class="line">    kernel = np.array([[0, -1, 0],</div><div class="line">                       [-1, 5, -1],</div><div class="line">                       [0, -1, 0]], np.float32)  <span class="comment"># kernel should be floating point type</span></div><div class="line">    </div><div class="line">    dst1 = <a class="code" href="../../d4/d86/group__imgproc__filter.html#ga27c049795ce870216ddfb366086b5a04">cv.filter2D</a>(src, -1, kernel)</div><div class="line">    <span class="comment"># ddepth = -1, means destination image has depth same as input image</span></div><div class="line">    </div><div class="line"></div><div class="line">    t = (time.time() - t)</div><div class="line">    <a class="code" href="../../df/d57/namespacecv_1_1dnn.html#a701210a0203f2786cbfd04b2bd56da47">print</a>(<span class="stringliteral">&quot;Built-in filter2D time passed in seconds:     %s&quot;</span> % t)</div><div class="line"></div><div class="line">    <a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&quot;Output&quot;</span>, dst1)</div><div class="line"></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">cv.waitKey</a>(0)</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga6b7fc1c1a8960438156912027b38f481">cv.destroyAllWindows</a>()</div><div class="line">    <span class="keywordflow">return</span> 0</div><div class="line"></div><div class="line"></div><div class="line"><span class="keywordflow">if</span> __name__ == <span class="stringliteral">&quot;__main__&quot;</span>:</div><div class="line">    main(sys.argv[1:])</div></div><!-- fragment -->  </div> <h2>基本方法</h2>
<p>现在让我们看看如何通过使用基本像素访问方法或使用<b><a class="el" href="../../d5/df1/group__imgproc__hal__functions.html#ga42c2468ab3a1238fbf48458c57169081">filter2D()</a></b>功能。</p>
<p>下面是一个函数：</p> <div class="newInnerHTML" title="cpp" style="display: none;">C++</div><div class="toggleable_div label_cpp" style="display: none;"> <div class="fragment"><div class="line"><span class="keywordtype">void</span> Sharpen(<span class="keyword">const</span> Mat&amp; myImage,Mat&amp; Result)</div><div class="line">{</div><div class="line">    <a class="code" href="../../db/de0/group__core__utils.html#gaf62bcd90f70e275191ab95136d85906b">CV_Assert</a>(myImage.depth() == <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga32b18d904ee2b1731a9416a8eef67d06">CV_8U</a>);  <span class="comment">// accept only uchar images</span></div><div class="line"><span class="comment"></span></div><div class="line">    <span class="keyword">const</span> <span class="keywordtype">int</span> nChannels = myImage.channels();</div><div class="line">    Result.create(myImage.size(),myImage.type());</div><div class="line"></div><div class="line">    <span class="keywordflow">for</span>(<span class="keywordtype">int</span> j = 1 ; j &lt; myImage.rows-1; ++j)</div><div class="line">    {</div><div class="line">        <span class="keyword">const</span> <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>* previous = myImage.ptr&lt;<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>&gt;(j - 1);</div><div class="line">        <span class="keyword">const</span> <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>* current  = myImage.ptr&lt;<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>&gt;(j    );</div><div class="line">        <span class="keyword">const</span> <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>* next     = myImage.ptr&lt;<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>&gt;(j + 1);</div><div class="line"></div><div class="line">        <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>* output = Result.ptr&lt;<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>&gt;(j);</div><div class="line"></div><div class="line">        <span class="keywordflow">for</span>(<span class="keywordtype">int</span> i= nChannels;i &lt; nChannels*(myImage.cols-1); ++i)</div><div class="line">        {</div><div class="line">            *output++ = <a class="code" href="../../db/de0/group__core__utils.html#gab93126370b85fda2c8bfaf8c811faeaf">saturate_cast</a>&lt;<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>&gt;(5*current[i]</div><div class="line">                         -current[i-nChannels] - current[i+nChannels] - previous[i] - next[i]);</div><div class="line">        }</div><div class="line">    }</div><div class="line"></div><div class="line">    Result.row(0).setTo(<a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">    Result.row(Result.rows-1).setTo(<a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">    Result.col(0).setTo(<a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">    Result.col(Result.cols-1).setTo(<a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">}</div></div><!-- fragment --><p>首先，我们要确保输入的图像数据是无符号字符格式。为此，我们使用<a class="el" href="../../db/de0/group__core__utils.html#gaf62bcd90f70e275191ab95136d85906b">cv::CV_Assert</a>函数中的表达式为false时抛出错误。</p><div class="fragment"><div class="line">    <a class="code" href="../../db/de0/group__core__utils.html#gaf62bcd90f70e275191ab95136d85906b">CV_Assert</a>(myImage.depth() == <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga32b18d904ee2b1731a9416a8eef67d06">CV_8U</a>);  <span class="comment">// accept only uchar images</span></div></div><!-- fragment --> </div>  <div class="newInnerHTML" title="java" style="display: none;">Java</div><div class="toggleable_div label_java" style="display: none;"> <div class="fragment"><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keywordtype">double</span> <a class="code" href="../../d6/d7d/namespacecv_1_1gapi_1_1own.html#a731d72310c89b732dcba8248d7b600b1">saturate</a>(<span class="keywordtype">double</span> x) {</div><div class="line">        <span class="keywordflow">return</span> x &gt; 255.0 ? 255.0 : (x &lt; 0.0 ? 0.0 : x);</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="keyword">public</span> Mat sharpen(Mat myImage, Mat Result) {</div><div class="line">        myImage.convertTo(myImage, CvType.CV_8U);</div><div class="line"></div><div class="line">        <span class="keywordtype">int</span> nChannels = myImage.channels();</div><div class="line">        Result.create(myImage.size(), myImage.type());</div><div class="line"></div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> j = 1; j &lt; myImage.rows() - 1; ++j) {</div><div class="line">            <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 1; i &lt; myImage.cols() - 1; ++i) {</div><div class="line">                <span class="keywordtype">double</span> sum[] = <span class="keyword">new</span> <span class="keywordtype">double</span>[nChannels];</div><div class="line"></div><div class="line">                <span class="keywordflow">for</span> (<span class="keywordtype">int</span> k = 0; k &lt; nChannels; ++k) {</div><div class="line"></div><div class="line">                    <span class="keywordtype">double</span> top = -myImage.get(j - 1, i)[k];</div><div class="line">                    <span class="keywordtype">double</span> bottom = -myImage.get(j + 1, i)[k];</div><div class="line">                    <span class="keywordtype">double</span> center = (5 * myImage.get(j, i)[k]);</div><div class="line">                    <span class="keywordtype">double</span> left = -myImage.get(j, i - 1)[k];</div><div class="line">                    <span class="keywordtype">double</span> right = -myImage.get(j, i + 1)[k];</div><div class="line"></div><div class="line">                    sum[k] = <a class="code" href="../../d6/d7d/namespacecv_1_1gapi_1_1own.html#a731d72310c89b732dcba8248d7b600b1">saturate</a>(top + bottom + center + left + right);</div><div class="line">                }</div><div class="line"></div><div class="line">                Result.put(j, i, sum);</div><div class="line">            }</div><div class="line">        }</div><div class="line"></div><div class="line">        Result.row(0).setTo(<span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">        Result.row(Result.rows() - 1).setTo(<span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">        Result.col(0).setTo(<span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">        Result.col(Result.cols() - 1).setTo(<span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line"></div><div class="line">        <span class="keywordflow">return</span> Result;</div><div class="line">    }</div></div><!-- fragment --><p>首先，我们要确保输入的图像数据是无符号的8位格式。</p><div class="fragment"><div class="line">        myImage.convertTo(myImage, CvType.CV_8U);</div></div><!-- fragment --> </div>  <div class="newInnerHTML" title="python" style="display: none;">Python</div><div class="toggleable_div label_python" style="display: none;"> <div class="fragment"><div class="line"><span class="keyword">def </span>is_grayscale(my_image):</div><div class="line">    <span class="keywordflow">return</span> len(my_image.shape) &lt; 3</div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">def </span>saturated(sum_value):</div><div class="line">    <span class="keywordflow">if</span> sum_value &gt; 255:</div><div class="line">        sum_value = 255</div><div class="line">    <span class="keywordflow">if</span> sum_value &lt; 0:</div><div class="line">        sum_value = 0</div><div class="line"></div><div class="line">    <span class="keywordflow">return</span> sum_value</div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">def </span>sharpen(my_image):</div><div class="line">    <span class="keywordflow">if</span> is_grayscale(my_image):</div><div class="line">        height, width = my_image.shape</div><div class="line">    <span class="keywordflow">else</span>:</div><div class="line">        my_image = <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cv.cvtColor</a>(my_image, cv.CV_8U)</div><div class="line">        height, width, n_channels = my_image.shape</div><div class="line"></div><div class="line">    result = np.zeros(my_image.shape, my_image.dtype)</div><div class="line">    </div><div class="line">    <span class="keywordflow">for</span> j <span class="keywordflow">in</span> range(1, height - 1):</div><div class="line">        <span class="keywordflow">for</span> i <span class="keywordflow">in</span> range(1, width - 1):</div><div class="line">            <span class="keywordflow">if</span> is_grayscale(my_image):</div><div class="line">                sum_value = 5 * my_image[j, i] - my_image[j + 1, i] - my_image[j - 1, i] \</div><div class="line">                            - my_image[j, i + 1] - my_image[j, i - 1]</div><div class="line">                result[j, i] = saturated(sum_value)</div><div class="line">            <span class="keywordflow">else</span>:</div><div class="line">                <span class="keywordflow">for</span> k <span class="keywordflow">in</span> range(0, n_channels):</div><div class="line">                    sum_value = 5 * my_image[j, i, k] - my_image[j + 1, i, k]  \</div><div class="line">                                - my_image[j - 1, i, k] - my_image[j, i + 1, k]\</div><div class="line">                                - my_image[j, i - 1, k]</div><div class="line">                    result[j, i, k] = saturated(sum_value)</div><div class="line">    </div><div class="line">    <span class="keywordflow">return</span> result</div></div><!-- fragment --><p>首先，我们要确保输入的图像数据是无符号的8位格式。</p><div class="fragment"><div class="line">my_image = <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cv.cvtColor</a>(my_image, cv.CV_8U)</div></div><!-- fragment --> </div> <p>我们创建一个与输入大小和类型相同的输出图像。正如你在照片中看到的<a class="el" href="../../db/da5/tutorial_how_to_scan_images.html#tutorial_how_to_scan_images_storing">storing</a>节，根据频道的数量，我们可能有一个或多个子列。</p>
 <div class="newInnerHTML" title="cpp" style="display: none;">C++</div><div class="toggleable_div label_cpp" style="display: none;"><p>我们将通过指针遍历它们，因此元素的总数取决于这个数。</p><div class="fragment"><div class="line">    <span class="keyword">const</span> <span class="keywordtype">int</span> nChannels = myImage.channels();</div><div class="line">    Result.create(myImage.size(),myImage.type());</div></div><!-- fragment --> </div>  <div class="newInnerHTML" title="java" style="display: none;">Java</div><div class="toggleable_div label_java" style="display: none;"> <div class="fragment"><div class="line">        <span class="keywordtype">int</span> nChannels = myImage.channels();</div><div class="line">        Result.create(myImage.size(), myImage.type());</div></div><!-- fragment --> </div>  <div class="newInnerHTML" title="python" style="display: none;">Python</div><div class="toggleable_div label_python" style="display: none;"> <div class="fragment"><div class="line">height, width, n_channels = my_image.shape</div><div class="line">result = np.zeros(my_image.shape, my_image.dtype)</div></div><!-- fragment -->  </div>  <div class="newInnerHTML" title="cpp" style="display: none;">C++</div><div class="toggleable_div label_cpp" style="display: none;"><p>我们将使用纯C[]操作符来访问像素。因为我们需要同时访问多行，所以我们将获取每一行的指针（前一行、当前行和下一行）。我们需要另一个指针指向保存计算的位置。然后只需使用[]操作符访问正确的项。为了将输出指针向前移动，我们只需在每次操作后增加（一个字节）：</p><div class="fragment"><div class="line">    <span class="keywordflow">for</span>(<span class="keywordtype">int</span> j = 1 ; j &lt; myImage.rows-1; ++j)</div><div class="line">    {</div><div class="line">        <span class="keyword">const</span> <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>* previous = myImage.ptr&lt;<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>&gt;(j - 1);</div><div class="line">        <span class="keyword">const</span> <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>* current  = myImage.ptr&lt;<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>&gt;(j    );</div><div class="line">        <span class="keyword">const</span> <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>* next     = myImage.ptr&lt;<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>&gt;(j + 1);</div><div class="line"></div><div class="line">        <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>* output = Result.ptr&lt;<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>&gt;(j);</div><div class="line"></div><div class="line">        <span class="keywordflow">for</span>(<span class="keywordtype">int</span> i= nChannels;i &lt; nChannels*(myImage.cols-1); ++i)</div><div class="line">        {</div><div class="line">            *output++ = <a class="code" href="../../db/de0/group__core__utils.html#gab93126370b85fda2c8bfaf8c811faeaf">saturate_cast</a>&lt;<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>&gt;(5*current[i]</div><div class="line">                         -current[i-nChannels] - current[i+nChannels] - previous[i] - next[i]);</div><div class="line">        }</div><div class="line">    }</div></div><!-- fragment --><p>在图像的边界上，上面的符号表示不存在的像素位置（比如负一-负一）。在这几点上，我们的公式是没有定义的。一个简单的解决方案是不在这些点上应用内核，例如，将边界上的像素设置为零：</p>
<div class="fragment"><div class="line">    Result.row(0).setTo(<a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">    Result.row(Result.rows-1).setTo(<a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">    Result.col(0).setTo(<a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">    Result.col(Result.cols-1).setTo(<a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div></div><!-- fragment --> </div>  <div class="newInnerHTML" title="java" style="display: none;">Java</div><div class="toggleable_div label_java" style="display: none;"><p>我们需要访问多个行和列，这可以通过向当前中心（i，j）加1或减1来完成。然后我们应用和，并将新值放入结果矩阵中。</p><div class="fragment"><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> j = 1; j &lt; myImage.rows() - 1; ++j) {</div><div class="line">            <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 1; i &lt; myImage.cols() - 1; ++i) {</div><div class="line">                <span class="keywordtype">double</span> sum[] = <span class="keyword">new</span> <span class="keywordtype">double</span>[nChannels];</div><div class="line"></div><div class="line">                <span class="keywordflow">for</span> (<span class="keywordtype">int</span> k = 0; k &lt; nChannels; ++k) {</div><div class="line"></div><div class="line">                    <span class="keywordtype">double</span> top = -myImage.get(j - 1, i)[k];</div><div class="line">                    <span class="keywordtype">double</span> bottom = -myImage.get(j + 1, i)[k];</div><div class="line">                    <span class="keywordtype">double</span> center = (5 * myImage.get(j, i)[k]);</div><div class="line">                    <span class="keywordtype">double</span> left = -myImage.get(j, i - 1)[k];</div><div class="line">                    <span class="keywordtype">double</span> right = -myImage.get(j, i + 1)[k];</div><div class="line"></div><div class="line">                    sum[k] = <a class="code" href="../../d6/d7d/namespacecv_1_1gapi_1_1own.html#a731d72310c89b732dcba8248d7b600b1">saturate</a>(top + bottom + center + left + right);</div><div class="line">                }</div><div class="line"></div><div class="line">                Result.put(j, i, sum);</div><div class="line">            }</div><div class="line">        }</div></div><!-- fragment --><p>在图像的边界上，上面的符号导致不存在像素位置（如（-1，-1））。在这几点上，我们的公式是没有定义的。一个简单的解决方案是不在这些点上应用内核，例如，将边界上的像素设置为零：</p>
<div class="fragment"><div class="line">        Result.row(0).setTo(<span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">        Result.row(Result.rows() - 1).setTo(<span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">        Result.col(0).setTo(<span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">        Result.col(Result.cols() - 1).setTo(<span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div></div><!-- fragment --> </div>  <div class="newInnerHTML" title="python" style="display: none;">Python</div><div class="toggleable_div label_python" style="display: none;"><p>我们需要访问多个行和列，这可以通过向当前中心（i，j）加1或减1来完成。然后我们应用和，并将新值放入结果矩阵中。</p><div class="fragment"><div class="line">    <span class="keywordflow">for</span> j <span class="keywordflow">in</span> range(1, height - 1):</div><div class="line">        <span class="keywordflow">for</span> i <span class="keywordflow">in</span> range(1, width - 1):</div><div class="line">            <span class="keywordflow">if</span> is_grayscale(my_image):</div><div class="line">                sum_value = 5 * my_image[j, i] - my_image[j + 1, i] - my_image[j - 1, i] \</div><div class="line">                            - my_image[j, i + 1] - my_image[j, i - 1]</div><div class="line">                result[j, i] = saturated(sum_value)</div><div class="line">            <span class="keywordflow">else</span>:</div><div class="line">                <span class="keywordflow">for</span> k <span class="keywordflow">in</span> range(0, n_channels):</div><div class="line">                    sum_value = 5 * my_image[j, i, k] - my_image[j + 1, i, k]  \</div><div class="line">                                - my_image[j - 1, i, k] - my_image[j, i + 1, k]\</div><div class="line">                                - my_image[j, i - 1, k]</div><div class="line">                    result[j, i, k] = saturated(sum_value)</div></div><!-- fragment --> </div> <h2>filter2D函数</h2>
<p>应用这样的过滤器在图像处理中非常常见，以至于在OpenCV中有一个函数负责应用掩码（在某些地方也称为内核）。为此，首先需要定义一个包含遮罩的对象：</p>
 <div class="newInnerHTML" title="cpp" style="display: none;">C++</div><div class="toggleable_div label_cpp" style="display: none;"> <div class="fragment"><div class="line">    Mat kernel = (Mat_&lt;char&gt;(3,3) &lt;&lt;  0, -1,  0,</div><div class="line">                                   -1,  5, -1,</div><div class="line">                                    0, -1,  0);</div></div><!-- fragment --> </div>  <div class="newInnerHTML" title="java" style="display: none;">Java</div><div class="toggleable_div label_java" style="display: none;"> <div class="fragment"><div class="line">        Mat kern = <span class="keyword">new</span> Mat(3, 3, CvType.CV_8S);</div><div class="line">        <span class="keywordtype">int</span> row = 0, col = 0;</div><div class="line">        kern.put(row, col, 0, -1, 0, -1, 5, -1, 0, -1, 0);</div></div><!-- fragment --> </div>  <div class="newInnerHTML" title="python" style="display: none;">Python</div><div class="toggleable_div label_python" style="display: none;"> <div class="fragment"><div class="line">    kernel = np.array([[0, -1, 0],</div><div class="line">                       [-1, 5, -1],</div><div class="line">                       [0, -1, 0]], np.float32)  <span class="comment"># kernel should be floating point type</span></div></div><!-- fragment --> </div> <p>然后打电话给<b><a class="el" href="../../d5/df1/group__imgproc__hal__functions.html#ga42c2468ab3a1238fbf48458c57169081">filter2D()</a></b>函数指定要使用的输入、输出图像和内核：</p>
 <div class="newInnerHTML" title="cpp" style="display: none;">C++</div><div class="toggleable_div label_cpp" style="display: none;"> <div class="fragment"><div class="line">    <a class="code" href="../../d5/df1/group__imgproc__hal__functions.html#ga42c2468ab3a1238fbf48458c57169081">filter2D</a>( src, dst1, src.depth(), kernel );</div></div><!-- fragment --> </div>  <div class="newInnerHTML" title="java" style="display: none;">Java</div><div class="toggleable_div label_java" style="display: none;"> <div class="fragment"><div class="line">        Imgproc.filter2D(src, dst1, src.depth(), kern);</div></div><!-- fragment --> </div>  <div class="newInnerHTML" title="python" style="display: none;">Python</div><div class="toggleable_div label_python" style="display: none;"> <div class="fragment"><div class="line">    dst1 = <a class="code" href="../../d4/d86/group__imgproc__filter.html#ga27c049795ce870216ddfb366086b5a04">cv.filter2D</a>(src, -1, kernel)</div><div class="line">    <span class="comment"># ddepth = -1, means destination image has depth same as input image</span></div></div><!-- fragment --> </div> <p>该函数甚至有第五个可选参数来指定内核的中心，第六个用于在将过滤后的像素存储到K中之前向其添加可选值，第七个用于确定在操作未定义的区域（边界）中执行什么操作。</p>
<p>这个函数更短，更不冗长，而且由于有一些优化，它通常比<em>手工编码法</em>. 例如，在我的测试中，第二个只花了13毫秒，而第一个只花了31毫秒。有点不同。</p>
<p>例如：</p>
<div class="image">
<img src="../../resultMatMaskFilter2D.png" alt="resultMatMaskFilter2D.png">
</div>
 <div class="newInnerHTML" title="cpp" style="display: none;">C++</div><div class="toggleable_div label_cpp" style="display: none;"><p>查看在我们的计算机上运行程序的实例<a href="http://www.youtube.com/watch?v=7PF1tAU9se4">YouTube频道</a>.</p><div align="center"><iframe title="Video" width="560" height="349" src="https://www.youtube.com/embed/7PF1tAU9se4?rel=0" frameborder="0" align="middle" allowfullscreen=""></iframe></div>  </div>  </div></div><!-- contents -->
<!-- HTML footer for doxygen 1.8.6-->
<!-- start footer part -->
<hr class="footer"><address class="footer"><small>Generated on Fri Apr 2 2021 11:36:34 for OpenCV by zsz<a href="http://www.doxygen.org/index.html">
<img class="footer" src="../../doxygen.png" alt="doxygen">
</a> 1.8.13
</small></address>
<script type="text/javascript">
//<![CDATA[
addTutorialsButtons();
//]]>
</script>
</body>
</html>
